﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace S_User.Redis
{
    public class RedisServer
    {
        private readonly IDatabase _redis;
        public RedisServer() 
        {
            //是本机，可以写成localhost或者127.0.0.1，但如果不是本机，这里需要填写rediso所在服务器的ip地址
            IConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localHost");
            _redis = connection.GetDatabase();
        }
        //批量操作
        public void HashSet<T>(string redisKey, string[] hashKeys, T[] values, int expired = 2)
        {
            _redis.HashSet(redisKey, hashKeys.Select((x, index) => new HashEntry(x, JsonSerializer.Serialize(values[index]))).ToArray());
        }
        //存放redis
        public void HashSet<T>(string redisKey, string hashKey, T value, int expired = 2)
        {
            var jsonStr = JsonSerializer.Serialize(value);
            _redis.HashSet(redisKey, hashKey, jsonStr);
            _redis.KeyExpire(redisKey, TimeSpan.FromHours(expired));
        }
        //修改
        public T HashGet<T>(string redisKey, string hashKey)
        {
            string jsonStr = _redis.HashGet(redisKey, hashKey);
            if (string.IsNullOrEmpty(jsonStr))
            {
                return default(T);
            }
            return JsonSerializer.Deserialize<T>(jsonStr);
        }

        //显示数据
        public List<T> HashGetAll<T>(string redisKey)
        {
            var list = _redis.HashGetAll(redisKey).Select(c => JsonSerializer.Deserialize<T>(c.Value)).ToList();
            return list;
        }
        //批量删除
        public void HashRemove(string redisKey, string hashKey)
        {
            _redis.HashDelete(redisKey, hashKey);
        }
        //单删
        public void Remove(string redisKey)
        {
            _redis.KeyDelete(redisKey);
        }
    }
}
